<template>
  <div class="company-list-page">
    <!-- 顶部导航栏 -->
    <!-- <div class="page-header">
      <div class="header-left" @click="$router.go(-1)">
        <van-icon name="arrow-left" size="18" color="#333"/>
      </div>
      <div class="header-title">监测现场处理</div>
      <div class="header-right"></div>
    </div> -->
    <van-nav-bar title="监测现场处理" left-text="返回" left-arrow fixed>
      <template #left>
        <van-icon
          name="arrow-left"
          size="18"
          color="#333"
          @click="$router.go(-1)"
        />
      </template>
      <template #right></template>
    </van-nav-bar>
    <!-- 筛选区域 -->
    <!-- <div class="filter-bar">
      <div class="filter-item" @click="showDistrictPicker = true">
        {{ district || "全部状态" }}
        <van-icon name="arrow-down" size="12" color="#999" />
      </div> -->
    <!-- 项目选择 -->
    <!-- <div class="filter-item" @click="showProjectNamePicker = true">
        {{ projectName || "全部项目" }}
        <van-icon name="arrow-down" size="12" color="#999" />
      </div>
    </div> -->
    <div class="dropDowm">
      <van-dropdown-menu active-color="#1989fa">
        <van-dropdown-item
          v-model="district"
          :options="statusList"
          @change="changeStatus"
        />
        <van-dropdown-item
          v-model="projectName"
          :options="projectList"
          @change="changeProject"
        />
      </van-dropdown-menu>
    </div>
    <!-- 表格表头 -->
    <div class="table-head">
      <div class="head-tit">点位号</div>
      <div class="head-tit">项目</div>
      <div class="head-tit">状态</div>
      <div class="head-tit">操作</div>
    </div>
    <div class="scroll-box">
      <van-pull-refresh v-model="refreshing" @refresh="onRefresh">
        <van-list
          :loading="loading"
          :finished="finished"
          :error="error"
          finished-text="没有更多了"
          loading-text="加载中..."
          error-text="请求失败，点击重试"
          @load="loadData"
          :immediate-check="false"
        >
          <div class="point-list">
            <div class="list-item" v-for="item in pointList" :key="item.id">
              <div>
                {{ item.id }}
                <van-icon name="location-o" color="#2194ff"></van-icon>
              </div>
              <div class="ellipsis">{{ item.projectName }}</div>
              <div>
                {{
                  item.status == 2 ? "有蚁" : item.status == 3 ? "灭杀中" : ""
                }}
              </div>
              <div
                v-if="item.status == '3' || item.status == '7'"
                style="color: #2194ff"
                @click="handleGo(item)"
              >
                处理
              </div>
              <div
                v-if="item.status == '2'"
                style="color: #2194ff"
                @click="handleGo(item)"
              >
                处理
              </div>
            </div>
          </div>
        </van-list>
      </van-pull-refresh>
    </div>

    <!-- 区域选择弹出层 -->
    <van-popup v-model="showDistrictPicker" position="bottom">
      <van-picker
        title="选择状态"
        :columns="districts"
        value-key="projectName"
        @confirm="selectDistrict"
        @cancel="showDistrictPicker = false"
        show-toolbar
      />
    </van-popup>
    <van-popup v-model="showProjectNamePicker" position="bottom">
      <van-picker
        title="选择项目"
        :columns="projectList"
        value-key="projectName"
        @confirm="selectProjectName"
        @cancel="showProjectNamePicker = false"
        show-toolbar
      />
    </van-popup>
  </div>
</template>
<script>
import { termite } from "@/api/index";
export default {
  name: "EnterprisePage",
  data() {
    return {
      district: "",
      projectName: "",
      showDistrictPicker: false,
      showProjectNamePicker: false,
      districts: ["全部状态", "处理中", "待上传", "有蚁"],
      // projectList: [{ projectName: "全部项目" }],
      loading: false,
      finished: false,
      error: false,
      refreshing: false,
      pageNum: 1,
      pageSize: 20,
      total: 0,
      pointList: [],
      value1: 0,
      value2: "a",
      statusList: [
        { text: "全部状态", value: "" },
        // { text: "处理中", value: "3" },
        // { text: "待上传", value: "7" },
        { text: "灭杀中", value: "3" },
        // { text: "待上传", value: "7" },
        { text: "有蚁", value: "2" },
      ],
      projectList: [{ text: "全部项目", value: "" }],
    };
  },
  created() {
    this.init();
    this.loadData();
    // 等待 token 就绪后再加载数据
    // this.$nextTick(() => {
    //   this.waitForTokenAndLoad();
    // });
  },
  methods: {
    // async waitForTokenAndLoad() {
    //   // 等待 token 就绪
    //   const { waitTokenReady } = await import("@/utils/request");
    //   await waitTokenReady();
    //   // token 就绪后再加载数据
    //   this.loadData();
    // },
    init() {
      termite.queryMonitorPointMbProjectName().then((res) => {
        console.log(res, "999000");
        if (res.errorCode === "000000") {
          res.data.forEach((element) => {
            this.projectList.push({
              text: element.projectName,
              value: element.projectName,
            });
          });
          // this.projectList = this.projectList.concat(res.data);
        }
      });
    },
    changeStatus(value) {
      this.district = value;
      this.resetList();
      this.loadData();
    },
    changeProject(value) {
      this.projectName = value;
      this.resetList();
      this.loadData();
    },
    selectDistrict(value) {
      this.district = value;
      this.showDistrictPicker = false;
      this.resetList();
      this.loadData();
    },
    selectProjectName(value) {
      this.projectName = value.projectName;
      this.showProjectNamePicker = false;
      this.resetList();
      this.loadData();
    },
    async loadData() {
      if (this.loading || this.finished) return;

      this.error = false;
      this.loading = true;
      const data = {
        status: this.district,
        projectName: this.projectName,
        pageNum: this.pageNum,
        pageSize: this.pageSize,
      };
      if (this.district == "全部状态") {
        data.status = "";
      }
      if (this.projectName == "全部项目") {
        data.projectName = "";
      }
      termite
        .queryMonitorPointMb(data)
        .then((res) => {
          console.log("res:", res);
          if (res.errorCode === "000000") {
            this.total = res.data.total;
            console.log(this.pointList, res.data.list);
            this.pointList = this.pointList.concat(res.data.list);
            if (this.pageNum * this.pageSize >= this.total) {
              // 数据已经加载完
              this.finished = true;
            }
            this.pageNum++;
          } else {
            // 接口返回业务失败，进入错误态，停止自动触发
            this.error = true;
          }
          this.loading = false;
          this.refreshing = false;
        })
        .catch((error) => {
          console.error("请求失败:", error);
          // 接口请求失败，进入错误态，停止自动触发
          this.error = true;
          this.loading = false;
          this.refreshing = false;
        });
      //   return;
      //   try {
      //     await new Promise(resolve => setTimeout(resolve, 1000));

      //     // 模拟总共有43条数据
      //     const totalItems = 43;
      //     const startIndex = (this.pageNum - 1) * this.pageSize;
      //     const endIndex = Math.min(startIndex + this.pageSize, totalItems);

      //     // 如果已经加载完所有数据
      //     if (startIndex >= totalItems) {
      //       this.finished = true;
      //       this.loading = false;
      //       return;
      //     }

      //     const mockData = Array.from(
      //       { length: endIndex - startIndex },
      //       (_, index) => ({
      //         id: `company_${startIndex + index + 1}`,
      //         number: `测试公司${startIndex + index + 1}`,
      //         project: "13800138000",
      //         status: "测试地址"
      //       })
      //     );

      //     this.pointList.push(...mockData);
      //     this.pageNum++;

      //     // 检查是否已经加载完所有数据
      //     if (endIndex >= totalItems) {
      //       this.finished = true;
      //     }
      //   } catch (error) {
      //     console.error("加载数据失败:", error);
      //   } finally {
      //     this.loading = false;
      //     this.refreshing = false;
      //   }
    },
    onRefresh() {
      this.refreshing = true;
      this.resetList();
      this.loadData();
    },
    resetList() {
      this.pageNum = 1;
      this.pointList = [];
      this.finished = false;
      this.error = false;
    },
    handleGo(item) {
      console.log(item);
      this.$router.push({
        name: "handleItem",
        params: { ...item },
      });
    },
  },
};
</script>

<style lang="less" scoped>
.company-list-page {
  background-color: #fff;
  height: 100vh;
  overflow-y: auto;
}
.page-header {
  display: flex;
  align-items: center;
  height: 44px;
  background-color: #fff;
  border-bottom: 1px solid #f0f0f0;
  position: sticky;
  top: 0;
  z-index: 100;
  padding: 0 16px;

  .header-left {
    width: 44px;
    height: 44px;
    display: flex;
    justify-content: center;
    align-items: center;
    margin-left: -16px;
    cursor: pointer;
  }

  .header-title {
    flex: 1;
    text-align: center;
    font-family:
      PingFangSC,
      PingFang SC;
    font-weight: 500;
    font-size: 17px;
    color: #333;
  }

  .header-right {
    width: 44px;
  }
}
.dropDowm {
  background-color: #fff;
  border-bottom: 1px solid #f0f0f0;
  position: sticky;
  top: 44px;
  z-index: 99;
  ::v-deep .van-dropdown-menu__bar {
    box-shadow: none !important;
  }
}
.filter-bar {
  display: flex;
  background-color: #fff;
  padding: 12px 16px;
  border-bottom: 1px solid #f0f0f0;
  position: sticky;
  top: 44px;
  z-index: 99;

  .filter-item {
    display: flex;
    width: 100px;
    align-items: center;
    gap: 4px;
    font-family:
      PingFangSC,
      PingFang SC;
    font-weight: 400;
    font-size: 14px;
    color: #333;
    cursor: pointer;
  }
}
.table-head {
  height: 45px;
  background: #e7f0f7;
  padding: 0 15px;
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 14px;
  text-align: center;
  color: #666;
  position: sticky;
  top: 92px;
  z-index: 89;
  .head-tit {
    flex: 1;
  }
}
.scroll-box {
  height: calc(100vh - 150px);
  margin-top: 45px;
  // overflow: hidden;
}
.point-list {
  padding: 0 15px;
  font-size: 14px;
  text-align: center;
  color: #333;
  .list-item {
    display: flex;
    justify-content: center;
    align-items: center;
    height: 45px;
    // background: #fff;
    border-bottom: 1px solid #f4f5fb;
    div {
      flex: 1;
      min-width: 0;
      text-align: center;
    }
    .ellipsis {
      overflow: hidden;
      white-space: nowrap;
      text-overflow: ellipsis;
    }
  }
}
</style>
